//
//  AddTaskViewController.swift
//  tdl
//
//  Created by Qingke on 16/4/12.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

//添加代理用于实现添加保存
protocol AddTaskDelegate:class {
    func addTaskViewController(viewController:AddTaskViewController,task:ToDo)
    func editTaskViewController(viewController:AddTaskViewController,task:ToDo)
}

class AddTaskViewController: UITableViewController {
    
    var editToTask:ToDo?

    @IBOutlet weak var saveButton: UIBarButtonItem!
    
    @IBOutlet weak var textField: UITextField!
    
    weak var addTaskDelegate:AddTaskDelegate?
    
    @IBAction func save(sender: AnyObject) {
        if let editToTask = editToTask {
            
            editToTask.name = textField.text!
            addTaskDelegate!.editTaskViewController(self, task: editToTask)
            
        } else {
            
            if let addTaskDelegate = addTaskDelegate {
                let task = ToDo()
                task.name = textField.text!
                addTaskDelegate.addTaskViewController(self, task: task)
            }

        }
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func cancel(sender: UIBarButtonItem) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        
        super.viewDidLoad()
        saveButton.enabled = false
        
        if let editToTask = editToTask {
            self.textField.text = editToTask.name
            self.navigationItem.title = "编辑任务"
        }
    }
    
    //点击添加即跳出输入
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        textField.becomeFirstResponder()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    //防止cell被选中
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        return nil
    }
      
    
}

//声明delegete代理
extension AddTaskViewController: UITextFieldDelegate {
    //防止输入为空
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let oldText:NSString = textField.text!
                let newText:NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
        
                if newText.length > 0 {
                    saveButton.enabled = true
                }else {
                    saveButton.enabled = false
                }
                return true
    }
    
}
